import { Form, Input, InputNumber, Modal } from 'antd';
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { ModalStatus } from '@/utils/utils';
import Hidden from '@/components/Hidden';

const ProductModal = props => {
  const {
    status,
    form: { getFieldDecorator, validateFields },
    onCancel,
    currentRecord,
    dispatch,
    addLoading,
    updateLoading,
  } = props;

  const handleOk = () => {
    validateFields(async (errors, values) => {
      if (errors) {
        return;
      }
      let success = false;
      if (status === ModalStatus.add) {
        success = await dispatch({
          type: 'product/AddProduct',
          product: values,
        });
      } else if (status === ModalStatus.update) {
        success = await dispatch({
          type: 'product/UpdateProduct',
          product: values,
        });
      }
      if (!success) {
        return;
      }
      dispatch({
        type: 'product/QueryProduct',
      });
      onCancel();
    });
  };
  return (
    <Modal
      title={status === ModalStatus.add ? '添加产品' : '编辑产品'}
      visible={status !== ModalStatus.closed}
      onCancel={onCancel}
      onOk={handleOk}
      maskClosable={false}
      destroyOnClose
      confirmLoading={addLoading || updateLoading}
    >
      <Hidden>
        <Form.Item>
          {getFieldDecorator('id', {
            initialValue: currentRecord ? currentRecord.id : undefined,
          })(<Input />)}
        </Form.Item>
      </Hidden>
      <Form.Item label="名称">
        {getFieldDecorator('name', {
          initialValue: currentRecord ? currentRecord.name : undefined,
          rules: [{ required: true, message: '请输入名称' }],
        })(<Input />)}
      </Form.Item>
      <Form.Item label="价格">
        {getFieldDecorator('price', {
          initialValue: currentRecord ? currentRecord.price : undefined,
          rules: [{ required: true, message: '请输入价格' }],
        })(<InputNumber style={{ width: '100%' }} />)}
      </Form.Item>
    </Modal>
  );
};

ProductModal.propTypes = {
  status: PropTypes.oneOf(Object.values(ModalStatus)).isRequired,
  currentRecord: PropTypes.object.isRequired,
  onCancel: PropTypes.func.isRequired,
};

export default connect(({ loading }) => ({
  addLoading: loading.effects['product/AddProduct'],
  updateLoading: loading.effects['product/UpdateProduct'],
}))(Form.create()(ProductModal));
